package com.pocketsweet;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.util.Log;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.GetCallback;
import com.pocketsweet.chatlib.controller.MolianContactManager;
import com.pocketsweet.model.MLOrder;
import com.pocketsweet.model.MLTestOrder;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.uilib.countDownTimer;
import com.pocketsweet.ui.uilib.countDownTimer.TimerListener;

public class MLOrderTimer {
    private static MLOrderTimer _self;
    public static List<Map<String, countDownTimer>> orderList = new ArrayList<Map<String, countDownTimer>>();// 正式订单list
    public static List<Map<String, countDownTimer>> testOrderList = new ArrayList<Map<String, countDownTimer>>();// 测式订单list

    private MLOrderTimer() {
    }

    public static void init() {
        _self = new MLOrderTimer();
    }

    public static MLOrderTimer getInstance() {
        return _self;
    }

    public static void getAllOrderTimer() {
        // 获取今天的试聊单
        getTodayTestOrder();
        // 获取正式单
        getOrder();

    }

    private static void getOrder() {
        AVQuery<MLOrder> orderquery = new AVQuery<MLOrder>("MLOrder");
        orderquery.whereEqualTo("status", C.ORDER_SATAUS_GOING);
        orderquery.whereEqualTo("sponsor", UserService.getCurrentUser());
        orderquery.findInBackground(new FindCallback<MLOrder>() {

            @Override
            public void done(final List<MLOrder> orders, AVException e) {
                if (e == null) {
                    if (orders.size() != 0) {
                        // 获取网络时间看是否超时了
                        AVCloud.callFunctionInBackground("getNetTime", null,
                                new FunctionCallback<Long>() {

                                    @Override
                                    public void done(Long time, AVException e) {
                                        if (e == null) {
                                            for (int i = 0; i < orders.size(); i++) {
                                                Long restTime;
                                                MLOrder order = orders.get(i);
                                                Long endTime = order.getStartTime()
                                                        .getTime()
                                                        + ((long) order.getPeriod())
                                                        * 60
                                                        * 1000;// 开始时间+20分钟

                                                Long nowTime = time;
                                                restTime = endTime - nowTime;

                                                if (restTime > 0) {
                                                    // 设置定时器
                                                    setOrderTimer(restTime, order);

                                                } else {
                                                    // 订单时间已经到了，但是状态不对
                                                    order.setStatus(C.ORDER_STATUS_FINISH);
                                                    order.saveInBackground();
                                                }

                                            }
                                        }
                                    }

                                });
                    }
                }
            }
        });

    }

    private static void getTodayTestOrder() {
        AVQuery<MLTestOrder> orderquery = new AVQuery<MLTestOrder>(
                "MLTestOrder");
        orderquery.whereEqualTo("status", C.ORDER_SATAUS_GOING);
        orderquery.whereEqualTo("sponsor", UserService.getCurrentUser());
        orderquery.findInBackground(new FindCallback<MLTestOrder>() {

            @Override
            public void done(final List<MLTestOrder> testOrders, AVException e) {
                if (e == null) {
                    if (testOrders.size() != 0) {
                        // 获取网络时间看是否超时了
                        AVCloud.callFunctionInBackground("getNetTime", null,
                                new FunctionCallback<Long>() {

                                    @Override
                                    public void done(Long time, AVException e) {
                                        if (e == null) {

                                            for (int i = 0; i < testOrders.size(); i++) {
                                                MLTestOrder testorder = testOrders
                                                        .get(0);
                                                Long restTime;

                                                Long endTime = testorder
                                                        .getStartTime().getTime() + 20 * 60 * 1000;// 开始时间+20分钟

                                                Long nowTime = time;
                                                restTime = endTime - nowTime;

                                                if (restTime > 0) {
                                                    // 设置定时器
                                                    setTestOrderTimer(restTime,
                                                            testorder);

                                                } else {
                                                    // 订单时间已经到了，但是状态不对
                                                    testorder
                                                            .setStatus(C.ORDER_STATUS_FINISH);
                                                    testorder.saveInBackground();
                                                }

                                            }
                                        }
                                    }

                                });
                    }
                }
            }
        });

    }

    private static void setTestOrderTimer(Long time, MLTestOrder testorder) {
        // 加载倒计时的
        final MLUser toUser = testorder.getWinner();
        countDownTimer timer = new countDownTimer(time);
        timer.setOnTimerListener(new TimerListener() {

            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                MolianContactManager.getInstance().saveNewGrayMsg(
                        toUser.getObjectId(), toUser.getNickname(),
                        C.GRAY_MEG_NORMAL_TIMEOUT_TEST, null);
                // 给对方发通知
                MolianContactManager.getInstance().sendCMDMsg(
                        UserService.getCurrentUser().getNickname(),
                        toUser.getObjectId(), C.ACTION_TESTORDER_LOVER_FINISH,
                        null);
            }
        });
        timer.startCountDown();

        // 不存在当前单
        int id = checkTestOrder(testorder.getWinner().getObjectId());
        if (id == -1) {
            Map<String, countDownTimer> ordermap = new HashMap<String, countDownTimer>();
            ordermap.put(testorder.getWinner().getObjectId(), timer);
            if (testOrderList != null) {
                testOrderList.add(ordermap);
            } else {
                testOrderList = new ArrayList<Map<String, countDownTimer>>();
                testOrderList.add(ordermap);
            }
        } else {
            // 存在
            if (id < orderList.size()) {
                orderList.remove(id);
                Map<String, countDownTimer> ordermap = new HashMap<String, countDownTimer>();
                ordermap.put(testorder.getWinner().getObjectId(), timer);
                testOrderList.add(ordermap);
            }
        }

    }

    // 判断是否存在该id的单
    private static int checkTestOrder(String id) {
        if (testOrderList != null) {
            if (testOrderList.size() > 0) {
                for (int i = 0; i < testOrderList.size(); i++) {
                    if (testOrderList.get(i).containsKey(id)) {
                        return i;
                    }
                }
            }
        }
        return -1;
    }

    public void initTimerByTestOrder(String orderId) {
        AVQuery<MLTestOrder> orderquery = new AVQuery<MLTestOrder>(
                "MLTestOrder");
        orderquery.getInBackground(orderId, new GetCallback<MLTestOrder>() {

            @Override
            public void done(final MLTestOrder testorder, AVException e) {
                if (e == null) {
                    AVCloud.callFunctionInBackground("getNetTime", null,
                            new FunctionCallback<Long>() {

                                @Override
                                public void done(Long time, AVException e) {
                                    if (e == null) {

                                        Long restTime;

                                        Long endTime = testorder.getStartTime()
                                                .getTime() + 20 * 60 * 1000;// 开始时间+20分钟

                                        Long nowTime = time;
                                        restTime = endTime - nowTime;

                                        if (restTime > 0) {
                                            // 设置定时器
                                            setTestOrderTimer(restTime, testorder);

                                        } else {
                                            // 订单时间已经到了，但是状态不对
                                            testorder
                                                    .setStatus(C.ORDER_STATUS_FINISH);
                                            testorder.saveInBackground();
                                        }
                                    }
                                }

                            });
                }
            }
        });

    }

    public void initTimerByOrder(String orderId) {
        AVQuery<MLOrder> orderquery = new AVQuery<MLOrder>("MLOrder");
        orderquery.getInBackground(orderId, new GetCallback<MLOrder>() {

            @Override
            public void done(final MLOrder order, AVException e) {
                if (e == null) {
                    AVCloud.callFunctionInBackground("getNetTime", null,
                            new FunctionCallback<Long>() {

                                @Override
                                public void done(Long time, AVException e) {
                                    if (e == null) {

                                        Long restTime;

                                        Long endTime = order.getStartTime()
                                                .getTime()
                                                + ((long) order.getPeriod())
                                                * 60
                                                * 1000;

                                        Long nowTime = time;
                                        restTime = endTime - nowTime;

                                        if (restTime > 0) {
                                            // 设置定时器
                                            setOrderTimer(restTime, order);

                                        } else {
                                            // 订单时间已经到了，但是状态不对
                                            order.setStatus(C.ORDER_STATUS_FINISH);
                                            order.saveInBackground();
                                        }
                                    }
                                }

                            });
                }
            }
        });
    }

    private static void setOrderTimer(Long time, MLOrder order) {
        // 加载倒计时的
        final MLUser toUser = order.getWinner();
        countDownTimer timer = new countDownTimer(time);
        timer.setOnTimerListener(new TimerListener() {

            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                MolianContactManager.getInstance().saveNewGrayMsg(
                        toUser.getObjectId(), toUser.getNickname(),
                        C.GRAY_MEG_NORMAL_TIMEOUT, null);
                // 给对方发通知
                MolianContactManager.getInstance()
                        .sendCMDMsg(UserService.getCurrentUser().getNickname(),
                                toUser.getObjectId(),
                                C.ACTION_ORDER_LOVER_FINISH, null);
            }
        });
        timer.startCountDown();
        // 判断当前的试聊是否正在进行，若正在进行则删除
        if (checkTestOrder(order.getWinner().getObjectId()) != -1) {
            testOrderList
                    .remove(checkTestOrder(order.getWinner().getObjectId()));
        }
        // 修改当前的单
        // 不存在当前单
        int id = checkOrder(order.getWinner().getObjectId());
        if (id == -1) {
            Map<String, countDownTimer> ordermap = new HashMap<String, countDownTimer>();
            ordermap.put(order.getWinner().getObjectId(), timer);
            if (orderList != null) {
                orderList.add(ordermap);
            } else {
                orderList = new ArrayList<Map<String, countDownTimer>>();
                orderList.add(ordermap);
            }
        } else {
            // 存在
            orderList.remove(id);
            Map<String, countDownTimer> ordermap = new HashMap<String, countDownTimer>();
            ordermap.put(order.getWinner().getObjectId(), timer);
            orderList.add(ordermap);

        }
    }

    // 判断是否存在该id的单
    private static int checkOrder(String id) {
        if (orderList != null) {
            if (orderList.size() > 0) {
                for (int i = 0; i < orderList.size(); i++) {
                    if (orderList.get(i).containsKey(id)) {
                        return i;
                    }
                }
            }
        }
        return -1;
    }

    // 清空这个cache，退出账号的时候用
    public void clear() {
        testOrderList = null;
        orderList = null;
    }

}
